// pages/friends/index.ts
import tran from "../../utils/language";
import {
    login,
    friendRequestList,
    presenceList,
    userMobile,
    allFriendList,
} from "../../utils/api.js";
import { handleImUserData } from "../../utils/index.js";
import dayjs from "dayjs";
Page({
    /**
     * 页面的初始数据
     */
    data: {
        _t: tran._t("friends"),
        _tBase: tran._t("base"),
        navBarHeight: getApp().globalData.navBarHeight,
        loading: false,
        hasMobile: false,
        token:
            getApp().globalData.token || wx.getStorageSync("loginInfo").token,
        recentlyList: [
            {
                avatarurl: "",
                nickname: "",
                puzzleUrl: "",
            },
        ],
        userData: [
            {
                userId: "",
                nickname: "",
                mbti: "",
                lastMessage: "",
                avatarurl: "",
                xmove: 0,
            },
        ],
        findFriendParams: {
            showDownPopup: false,
        },
        blockList: [],
        friendRequestNum: 0,
        userInfo: {},
        completedStep: 0,
        popupParams: {
            showPopup: false,
        },
        mobileCode: "",
        filterData: [
            { text: "找个搭子一起玩", key: "321231", selectFlag: true },
            { text: "找个师父学点啥", key: "321431", selectFlag: false },
            { text: "找个朋友聊聊天", key: "3216431", selectFlag: false },
        ],
        allUserDataList: [] as any, // 好友列表
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        this.setData({
            recentlyList: [],
            userData: [],
        });
        const isLoginFlag = this.isLogin();
        // 判断是否登录
        if (isLoginFlag) {
            // this.getRecentlyList()
            this.getFriendList();
            this.getImData();
        }
    },
    isRegisterFn() {
        const loginInfo = wx.getStorageSync("loginInfo");
        const { popupParams } = this.data;
        if (loginInfo.completedStep == 5) {
            return true;
        } else {
            popupParams.showPopup = true;
            console.log("走这里", popupParams);
            this.setData({
                popupParams,
                completedStep: loginInfo.completedStep,
                hasMobile: loginInfo.hasMobile,
            });
            return false;
        }
    },
    getUserStatus(arr: any) {
        const userIds: any = [];
        arr.length > 0 &&
            arr.map((item: any) => {
                userIds.push(item.userId);
            });
        let userList: any = JSON.parse(JSON.stringify(userIds));
        const params = {
            userIds: userList || [],
        };
        presenceList(params).then((res: any) => {
            let list: any = []; // 消息列表
            let list3: any = []; // 最近联系人的列表
            arr.length > 0 &&
                arr.map((item: any, index: any) => {
                    const userObj = res.filter(
                        (item1: any) => item1.userId == item.userId
                    )[0];
                    if (item.lastMessage.type == "img") {
                        item.lastMessageText = "[图片]";
                    } else if (item.lastMessage.type == "video") {
                        item.lastMessageText = "[视频]";
                    } else if (item.lastMessage.type == "audio") {
                        item.lastMessageText = "[语音]";
                    } else {
                        item.lastMessageText = item.lastMessage.msg;
                    }
                    // 说明有用户属性
                    if (userObj && Object.keys(userObj).length > 0) {
                        item.avatarurl = userObj.avatar;
                        item.puzzleUrl = userObj.personalityAvatar;
                        item.nickname = userObj.pushName;
                        item.timeText = this.handleDateTime(
                            item.lastMessage.time
                        );
                        const listObj = {
                            ...item,
                            ...userObj,
                        };
                        list.push(listObj);
                        if (index < 6) {
                            list3.push(listObj);
                        }
                    } else {
                        // 说明没有用户属性，可能被注销了
                        const listObj = {
                            ...item,
                            ...userObj,
                        };
                        list.push(listObj);
                    }
                });
            this.setData({
                userData: list,
                recentlyList: list3,
            });
        });
    },
    /**
     * 监听IM环信
     */
    getaddListen() {
        const that = this;
        // that.getBlockList();
        wx.conn.listen({
            onReceivedMessage: (message: any) => {
                console.log("处理接收到的所有消息", message);
                // 处理接收到的所有消息
                setTimeout(() => {
                    that.getList();
                    getApp().getTotalUnreadCount();
                }, 500);
            },
            onGroupEvent: (message: any) => {
                console.log("处理接收到的所有消息123", message);
                // 处理接收到的所有消息
                setTimeout(() => {
                    that.getList();
                    getApp().getTotalUnreadCount();
                }, 500);
            },
            onReadMessage: (message: any) => {
                console.log("Received read receipt:", message);
                // 处理已读回执
            },
            onRoster: (message: any) => {
                console.log("Roster updated:", message);
                // 处理好友列表更新事件
                that.getFriendRequestList();
                that.getRecentlyList();
            },
            onPresenceStatusChange: (message: any) => {
                console.log("Presence status changed:", message);
                // 处理在线状态变更事件
            },
            // 当前用户收到好友请求。用户 B 向用户 A 发送好友请求，用户 A 收到该事件。
            onContactInvited: function (msg: any) {
                // 处理好友列表更新事件
                that.getFriendRequestList();
                that.getRecentlyList();
            },
            // 当前用户被其他用户从联系人列表上移除。用户 B 将用户 A 从联系人列表上删除，用户 A 收到该事件。
            onContactDeleted: function (msg: any) {
                // 处理好友列表更新事件
                that.getFriendRequestList();
                that.getRecentlyList();
            },
            // 当前用户新增了联系人。用户 B 向用户 A 发送好友请求，用户 A 同意该请求，用户 A 收到该事件，而用户 B 收到 `onContactAgreed` 事件。
            onContactAdded: function (msg: any) {
                // 处理好友列表更新事件
                that.getFriendRequestList();
                that.getRecentlyList();
            },
            // 当前用户发送的好友请求被拒绝。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，拒绝加好友，则用户 A 收到该事件。
            onContactRefuse: function (msg: any) {
                // 处理好友列表更新事件
                that.getFriendRequestList();
                that.getRecentlyList();
            },
            // 当前用户发送的好友请求经过了对方同意。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，同意加好友，则用户 A 收到该事件。
            onContactAgreed: function (msg: any) {
                // 处理好友列表更新事件
                that.getFriendRequestList();
                that.getRecentlyList();
            },
        });
    },
    /**
     * 获取好友请求数量
     */
    getFriendRequestList() {
        const params = {};
        this.setData({
            loading: false,
        });
        friendRequestList(params).then((res: any) => {
            this.setData({
                loading: false,
                friendRequestNum: res.length || 0,
            });
        });
    },
    /**
     * 删除某条消息会话后执行
     */
    deleteProduct() {
        this.getList();
    },
    /**
     * 获取最近联系人列表
     */
    getRecentlyList() {
        // 这里暂时不要，最近联系人列表是从消息列表中获取的数据（java让从那个接口获取）
        // this.setData({
        //   recentlyList: []
        // })
        // const that = this
        // wx.conn.getAllContacts().then((res: any) => {
        //   that.getUserInfo(res.data, '1')
        // })
        //   .catch((e: any) => {
        //     console.log(e, 'getAllContacts failed');
        //   });
    },
    closePopup() {
        this.setData({ popupParams: { showPopup: false } });
    },
    getToken() {
        this.setData({
            token:
                getApp().globalData.token ||
                wx.getStorageSync("loginInfo").token,
        });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // getApp().getTotalUnreadCount();
        // this.setData({
        //     recentlyList: [],
        //     userData: [],
        // });
        const isLoginFlag = this.isLogin();
        if (isLoginFlag) {
            this.getImData();
            this.getFriendRequestList();
            getApp().updateTabBar(getApp().globalData.totalUnread);
            getApp().getTotalUnreadCount();
        }
        if (typeof this.getTabBar === "function" && this.getTabBar()) {
            this.getTabBar().setData({
                activeKey: "friends",
            });
        }
    },
    /**
     * 查询黑名单列表
     */
    getBlockList() {
        wx.conn.getBlocklist().then((res: any) => {
            this.setData({
                blockList: res.data,
            });
        });
    },
    // 从这里开始
    isLogin() {
        const userInfo = wx.getStorageSync("userInfo");
        const loginInfo = wx.getStorageSync("loginInfo");
        if (userInfo && Object.keys(userInfo).length > 0) {
            this.setData({
                userInfo,
                completedStep: loginInfo.completedStep,
                hasMobile: loginInfo.hasMobile,
                token: true,
            });
            return true;
        } else {
            this.setData({
                userInfo,
                completedStep: 0,
                hasMobile: false,
                token: false,
            });
            return false;
        }
    },
    /**
     * 跳转去注册
     */
    goRegister() {
        const { popupParams } = this.data;
        this.closePopup();
        popupParams.showPopup = false;
        this.setData({
            popupParams,
        });
        const that = this;
        that.jumpRegisterPage();
    },
    getPhoneNumber(e: baseEvent) {
        const that = this;
        if (e.detail.errMsg === "getPhoneNumber:ok") {
            // 获取到加密数据
            const { encryptedData, iv, code } = e.detail;
            that.setData(
                {
                    mobileCode: code,
                },
                () => {
                    that.getLoginToken(2);
                }
            );
            // 调用登录的接口
            // that.getMobile()
        } else {
            console.warn("用户拒绝授权");
        }
    },
    jumpRegisterPage() {
        const loginInfo = wx.getStorageSync("loginInfo");
        let completedStep = 0;
        if (loginInfo) {
            completedStep = loginInfo.completedStep;
        }
        if (loginInfo.completedStep == 5) {
            return false;
        }
        // completedStep没完成的步骤
        if (completedStep == 0) {
            // 第一个步骤没完成
            getApp().globalData.profileFrom = "register";
            wx.navigateTo({
                url: "/pages/profile/create-account/index?type=register",
            });
        } else if (completedStep == 1) {
            // 第二个步骤没完成
            getApp().globalData.profileFrom = "register";
            wx.navigateTo({
                url: "/pages/profile/personalization/index?type=register",
            });
        } else if (completedStep == 2) {
            getApp().globalData.profileFrom = "register";
            wx.navigateTo({
                url: "/pages/profile/interests-skills/index?type=register",
            });
        } else if (completedStep == 3) {
            getApp().globalData.profileFrom = "register";
            wx.navigateTo({
                url: "/pages/profile/proficiency/index?type=register",
            });
        } else if (completedStep == 4) {
            getApp().globalData.profileFrom = "register";
            wx.navigateTo({
                url: "/pages/profile/personality-type/index?type=register",
            });
        } else {
            getApp().globalData.profileFrom = "register";
            wx.navigateTo({
                url: "/pages/profile/personality-type/index?type=register",
            });
        }
    },

    /**
     * 拿到token
     */
    getLoginToken(getMobileFlag: any) {
        const that = this;
        wx.login({
            success(res1) {
                if (res1.code) {
                    // 调用登录的接口
                    const params = {
                        code: res1.code,
                    };
                    login(params).then((res: any) => {
                        const { header, data } = res;
                        let loginInfo = data.data;
                        let token =
                            header["Frieneed-Mini-Program-Satoken"] ||
                            header["frieneed-mini-program-satoken"];
                        let key =
                            header["Access-Control-Expose-Headers"] ||
                            header["access-control-expose-headers"]; // 用户的token放在response里面返回的
                        let obj = {
                            token,
                            key,
                            ...loginInfo,
                        };
                        that.setData({
                            completedStep: obj.completedStep,
                            hasMobile: loginInfo.hasMobile,
                        });
                        wx.setStorage({
                            key: "loginInfo",
                            data: obj,
                            success() {
                                // 调用获取个人信息的接口
                                getApp().getUserInfo();
                                if (getMobileFlag == 2) {
                                    // 获取用户手机号
                                    that.getMobile();
                                }
                            },
                        });
                    });
                } else {
                    wx.showToast({
                        title: "网络异常",
                        icon: "none",
                    });
                }
            },
        });
    },
    /**
     * 调用更新手机号的接口
     */
    getMobile() {
        const that = this;
        const params = {
            code: this.data.mobileCode,
        };
        userMobile(params).then((res: any) => {
            const { popupParams } = that.data;
            popupParams.showPopup = false;
            // 关闭弹框
            that.setData({ popupParams, hasMobile: true });
            let loginInfo = wx.getStorageSync("loginInfo");
            loginInfo.hasMobile = true;
            wx.setStorageSync("loginInfo", loginInfo);
            // getApp().getUserInfo()
            that.goRegister();
        });
    },
    /**
     * 获取好友列表
     */
    getFriendList() {
        allFriendList({})
            .then((res) => {
                this.getList();
                if (res) {
                    res.length > 0 &&
                        res.map((item: any) => {
                            item.nickname = item.pushName;
                            item.avatarurl = item.avatar;
                            item.puzzleUrl = item.personalityAvatar;
                        });
                    this.setData({
                        allUserDataList: res,
                    });
                } else {
                    this.setData({
                        allUserDataList: [],
                    });
                }
            })
            .catch((err) => {
                this.getList();
            });
    },
    /**
     * 获取IM是否登录
     */
    async getImData() {
        const that = this;
        let wxIm = wx.conn;
        // 判断是否IM连接成功
        if (wxIm) {
            await this.isLogin();
            await this.getFriendList();
            // await this.getList();
            await this.getFriendRequestList();
            // await this.getRecentlyList()
            await this.getBlockList();
            this.getaddListen();
            this.getToken();
            // 此处表示已查到im,就停止
            return;
        } else {
            // 如果没有wx.im，说明im还没连接成功，就再次调用getImData方法继续查
            setTimeout(() => {
                that.getImData();
            }, 500);
        }
    },
    /**
     * 获取用户属性
     * @param arr
     */
    getUserInfo(arr: any, type: string) {
        const userIds: any = [];
        arr.length > 0 &&
            arr.map((item: any) => {
                userIds.push(item.userId);
            });
        let userList: any = JSON.parse(JSON.stringify(userIds));
        this.setData({
            loading: false,
        });
        wx.conn.fetchUserInfoById(userIds).then((res: any) => {
            console.log("====================================");
            console.log(res);
            console.log("====================================");
            this.setData({
                loading: false,
            });
            const userInfoList = handleImUserData(userList, res.data);
            if (type == "1") {
                // 最近联系人
                this.setData({
                    // recentlyList: userInfoList // 暂时不要这里，在下面赋值
                });
            } else {
                // 消息列表
                let list: any = [];
                arr.forEach((item: any) => {
                    const userObj = userInfoList.filter(
                        (item1: any) => item1.userId == item.userId
                    )[0];
                    const extData = userObj.ext ? JSON.parse(userObj.ext) : {};
                    if (this.data.allUserDataList) {
                        const i = this.data.allUserDataList.findIndex(
                            (v: any) => v.userId === item.userId
                        );
                        item.onlineStatus =
                            i != -1
                                ? this.data.allUserDataList[i].onlineStatus
                                : "OFFLINE";
                    }
                    if (item.lastMessage.type == "img") {
                        item.lastMessageText = "[图片]";
                    } else if (item.lastMessage.type == "video") {
                        item.lastMessageText = "[视频]";
                    } else if (
                        item.lastMessage.type == "custom" &&
                        item.lastMessage.customExts.type === "audio"
                    ) {
                        item.lastMessageText = "[语音]";
                    } else {
                        item.lastMessageText = item.lastMessage.msg;
                    }
                    item.timeText = this.handleDateTime(item.lastMessage.time);
                    const listObj = {
                        ...item,
                        ...userObj,
                        ...extData,
                    };
                    list.push(listObj);
                });
                console.log(list);
                const list2 = JSON.parse(JSON.stringify(list));
                this.setData({
                    userData: list,
                    recentlyList: list2.slice(0, 5),
                });
            }
        });
    },
    getSubAuth() {
        wx.getSetting({
            withSubscriptions: true, // 查询订阅消息的授权状态
            success(res) {
                console.log("授权信息:", res);
                // 检查订阅消息的授权状态
                if (res.subscriptionsSetting) {
                    const { mainSwitch, itemSettings } =
                        res.subscriptionsSetting;

                    if (mainSwitch) {
                        console.log("用户已开启订阅消息");

                        if (itemSettings) {
                            for (let templateId in itemSettings) {
                                console.log(
                                    `模板 ${templateId} 的授权状态:`,
                                    itemSettings[templateId]
                                );
                            }
                        }
                    } else {
                        console.log("用户已关闭所有订阅消息");
                    }
                }
            },
            fail(err) {
                console.error("获取授权状态失败:", err);
            },
        });
        wx.requestSubscribeMessage({
            tmplIds: [
                "oG7LlygwRry-ZpsPe2iL0ZMppxtPLOqwUnKhfWvSrTU",
                "oG7LlygwRry-ZpsPe2iL0Q0rHy44N5sXV4KwDIxvVG8",
            ],
            async success(res) {
                console.log(res);
            },
            fail: (err) => {
                console.log(err);
            },
        });
    },
    userTap(e: any) {
        // this.getSubAuth();
        const { info } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `/pages/profile/userChat/index?info=${JSON.stringify(info)}`,
        });
    },
    /**
     * 跳转去添加好友列表
     */
    goAddFriend() {
        wx.navigateTo({
            url: "/pages/profile/addFriendList/index",
        });
    },

    /**
     * 处理时间
     * @param time
     */
    handleDateTime(time: any) {
        const today = dayjs().format("YYYY-MM-DD");
        const yesterday = dayjs().subtract(1, "day").format("YYYY-MM-DD");
        const timeText = dayjs(time).format("YYYY-MM-DD");

        if (today == timeText) {
            return "今天";
        } else if (yesterday == timeText) {
            return "昨天";
        } else {
            return dayjs(time).format("YYYY/MM/DD");
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        const query = wx.createSelectorQuery();
        query
            .select(".weui-navigation-bar")
            .boundingClientRect((rect) => {
                console.log(rect, " 盒子");
                if (rect) {
                    this.setData({
                        navBarHeight: rect.height,
                    });
                }
            })
            .exec();
    },

    /**
     * 获取消息列表
     */
    getList() {
        const params = {
            pageSize: 500, // pageSize: 每页期望获取的会话数量。取值范围为 [1,50]，默认为 `20`。
            cursor: "", // cursor：开始获取数据的游标位置。若传空字符串（''），SDK 从最新活跃的会话开始获取。
        };
        this.setData({
            loading: false,
        });
        wx.conn.getServerConversations(params).then((res: any) => {
            this.setData({
                loading: false,
            });
            const { conversations, cursor } = res.data;
            const userList: any = [];
            if (conversations && conversations.length) {
                conversations.map((item: any) => {
                    item.userId = item.conversationId;
                    // 产品说，只展示用户发过来的消息，不展示群组的，所以要过滤出用户的消息，群组的不能展示上去
                    if (item.conversationType == "singleChat") {
                        // 用户单聊
                        userList.push(item);
                    }
                });
            }
            // 获取用户属性
            this.getUserInfo(userList, "2");
        });
    },
    /**
     * 登录
     */
    async getLogin() {
        const that = this;
        // wx.login({
        //   success(res1) {
        //     if (res1.code) {
        //       // 调用登录的接口
        //       const params = {
        //         code: res1.code
        //       }
        //       login(params).then((res: any) => {
        //         console.log(res, '登录');
        //         // 关闭弹框
        //         wx.showToast({
        //           title: '登录成功'
        //         })
        //         const { header, data } = res
        //         let loginInfo = data.data
        //         let token = header['Frieneed-Mini-Program-Satoken']
        //         let key = header['Access-Control-Expose-Headers'] // 用户的token放在response里面返回的
        //         let obj = {
        //           token,
        //           key,
        //           ...loginInfo
        //         }
        //         that.setData({
        //           token: token
        //         })
        //         wx.setStorage({
        //           key: "loginInfo",
        //           data: obj
        //         })
        //       })
        //     } else {
        //       wx.showToast({
        //         title: '网络异常',
        //         icon: 'none'
        //       })
        //     }
        //   }
        // })
        await getApp().getLogin();
        this.getImData();
        setTimeout(() => {
            this.getToken();
        }, 1000);
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        console.log("下拉");
        // 关闭
        wx.hideNavigationBarLoading();
        this.getImData();
        this.getFriendRequestList();
        // 停止下拉刷新
        wx.stopPullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},

    closeFilterDownPopup() {
        const { findFriendParams } = this.data;
        findFriendParams.showDownPopup = false;
        this.setData({ findFriendParams: findFriendParams });
    },
    toSelectPage(e: any) {
        const currentIndex = e.target.dataset.index;
        const { filterData } = this.data;
        filterData.length > 0 &&
            filterData.map((item: any, index: any) => {
                if (index === currentIndex) {
                    item.selectFlag = true;
                } else {
                    item.selectFlag = false;
                }
            });
        this.setData({
            filterData,
        });
        const userInfo = wx.getStorageSync("userInfo");
        if (userInfo && Object.keys(userInfo).length > 0 && userInfo.userId) {
            if (currentIndex == 0) {
                // 找个搭子一起玩
                wx.navigateTo({
                    url: "/pages/profile/findPartner/index",
                });
            } else if (currentIndex == 1) {
                // 找个师傅学点啥
                wx.navigateTo({
                    url: "/pages/profile/masterStudy/index",
                });
            } else if (currentIndex == 2) {
                // 找个朋友聊聊天
                wx.navigateTo({
                    url: "/pages/profile/findFriend/index",
                });
            }
        }
    },
    goShield() {
        wx.navigateTo({
            url: "/pages/profile/shieldUserList/index",
        });
    },
    addTap() {
        const { findFriendParams } = this.data;
        const flag = this.isRegisterFn();
        if (flag) {
            findFriendParams.showDownPopup = true;
            this.setData({ findFriendParams: findFriendParams });
        }
    },
    // 点击查看全部，跳转好友列表
    goFindFriend() {
        const flag = this.isRegisterFn();
        if (flag) {
            wx.navigateTo({
                url: "/pages/profile/friendList/index",
            });
        }
    },
    methods: {},
});
